class TableSelection {
	constructor(hook, config = {}, selectedRowKeys = [], selectedRows = []) {
		this.hook = hook;
		// 初始化的时候，最好同步传入keys和rows
		this.selectedRowKeys = selectedRowKeys;
		this.selectedRows = selectedRows;
		// ============================================
		if (typeof config === 'function') {
			this.config = config(this) || {};
		} else {
			this.config = config;
		}
		// ============================================
		const { $ref } = hook.$m;
		this.rowSelection = $ref({
			selectedRowKeys,
			type: 'checkbox',
			...this.config,
			onChange: (...arg) => this.changeSelection(...arg),
		});
	}
	// keys为当前页中选中的项
	async changeSelection(keys, selectedRows, type) {
		const { onChange } = this.config;
		try {
			await onChange?.(keys, selectedRows, type);
			this.selectedRowKeys = keys;
			this.selectedRows = selectedRows;
			this.type = type;
			this.setKeys();
		} catch (error) {
			// 用户可以手动阻止知否执行本操作
			console.error(error);
		}
	}
	addKey(key) {
		this.selectedRowKeys = [...this.selectedRowKeys, key];
		this.setKeys();
	}
	removeKey(key) {
		this.selectedRowKeys = this.selectedRowKeys.filter((key) => !key);
		this.setKeys();
	}
	addKeys(keys) {
		this.selectedRowKeys = [...this.selectedRowKeys, ...keys];
		this.setKeys();
	}
	removeKeys(keys) {
		this.selectedRowKeys = this.selectedRowKeys.filter((key) => !keys.includes(key));
		this.setKeys();
	}
	echoKeys(keys = []) {
		this.selectedRowKeys = keys;
		this.setKeys();
	}
	setKeys() {
		this.rowSelection.value = {
			...this.rowSelection.value,
			selectedRowKeys: this.selectedRowKeys,
		};
	}
}

export default TableSelection;